package com.hph.demo;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.CharsetUtil;

import java.util.List;

/**
 * 自定义解码器
 * @author 10499
 */
public class MessageDecoder extends ByteToMessageDecoder {

    private int len;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

        System.out.println("自定义解码器被调用！！！");
        System.out.println(in);
        int m = in.readableBytes();
        if(m >= 4) {
            if(len == 0) {
                len = in.readInt();
            }
            if(in.readableBytes() < len) {
                return;
            }
            byte[] bytes = new byte[len];
            in.readBytes(bytes);
            MessageDTO messageDTO = new MessageDTO();
            messageDTO.setLen(len);
            messageDTO.setName(bytes);
            out.add(messageDTO);
        }
        len = 0;
    }
}
